#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

/*
 *  线程的同步：要求reversMsg函数在printfMsg函数前执行
 *  1. 基于多个条件变量实现，真实条件是flag. flag=0时reverseMsg函数执行，flag=1时printfMsg函数执行
 *  2. 其实单个就可以实现同步 此处测试下多个条件变量的写法
 reversMsg--------
printfMsg--------
buf : 987654321
reversMsg--------
printfMsg--------
buf : 123456789
reversMsg--------
printfMsg--------
buf : 987654321

*/

#define N 64

typedef struct message {
	char buf[N];
	int len;
}msg_t;

//真实判断条件
int flag = 0;
//定义互斥锁
pthread_mutex_t gmutex;
//条件变量
pthread_cond_t condPrint = PTHREAD_COND_INITIALIZER;
pthread_cond_t condReverse = PTHREAD_COND_INITIALIZER;

void * reverseMsg(void *);
void * printfMsg(void *);

int main(int argc, char * argv[]){
	msg_t msg = {"123456789", 9};
	pthread_t tid[2];

	pthread_mutex_init(&gmutex, NULL);
	pthread_create(&tid[0], NULL, reverseMsg, (void *)&msg);
	pthread_create(&tid[1], NULL, printfMsg, (void *)&msg);
	
	pthread_join(tid[0], NULL);
	pthread_join(tid[1], NULL);

	return 0;
}

//反转字符串 flag=0时执行
void * reverseMsg(void * arg){
	msg_t * msg = (msg_t *)arg;
	int i = 0;
	char tmpChar;

	while(1){
		pthread_mutex_lock(&gmutex);
		while(flag != 0){
			//condPrint: flag = 0的条件变量
			pthread_cond_wait(&condPrint, &gmutex);
		}
		printf("reversMsg--------\n");
		for(i = 0 ; i < msg->len / 2 ; i++){
			tmpChar = msg->buf[i];
			msg->buf[i] = msg->buf[msg->len - i - 1];
			msg->buf[msg->len - i - 1] = tmpChar;
		}
		flag = 1;
		//唤醒condReverse
		pthread_cond_signal(&condReverse);
		pthread_mutex_unlock(&gmutex);
	}
	return NULL;
}

//打印字符串 flag=1
void * printfMsg(void * arg){
	msg_t * msg = (msg_t *)arg;
	while(1){
		pthread_mutex_lock(&gmutex);
		while(flag != 1){
			//condReverse: flag = 1的条件变量
			pthread_cond_wait(&condReverse, &gmutex);
		}
		printf("printfMsg--------\n");
		printf("buf : %s\n", msg->buf);
		flag = 0;
		//唤醒condPrint
		pthread_cond_signal(&condPrint);
		pthread_mutex_unlock(&gmutex);
		sleep(1);
	}

	return NULL;
}
